package com.ltu.ai.sparkdesk.websocket.legal;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;
import java.util.concurrent.CountDownLatch;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ltu.ai.sparkdesk.websocket.AiContextManager;
import com.ltu.ai.sparkdesk.websocket.AiContextManager.IatContext;
import com.ltu.service.OssService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;



@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LegalSocketService{
	
    private final AiContextManager aiContextManager;
    // 语音识别成文字
 	private static final String HostUrl = "wss://xinghuolegal.com/lc-front/api/v1/endPoint";
    // appid
	private static final String APPID = "9d304fcc-ab51-4fba-8eca-5281d83f2758";
    // appid对应的secret_key
	private static final String SECRET_KEY = "EieULCZUKa66SYqO2D4mVKsOppbI8Qav";
	private static final String API_NAME = "hm";
	private static final String API_TYPE = "api";
 

// 	@Async(value = "customServiceExecutor" )
    public void  createAIClient(String deviceMac) {
		try {
			URI	serverUri = new URI(HostUrl);
			IatContext iatContext =	AiContextManager.IatContextMap.get(deviceMac);
			 Map<String,String> headers = new HashMap<String, String>(1);
			  // 请求头的鉴权字符串 api!${appName}!${token} 假设appName=a,token=B，sec-websocket-protocol = "api!a!B"
			 String token  = TokenUtil.getAuthToken(APPID,API_TYPE,SECRET_KEY);
			 String authHeader = "api!"+API_NAME+"!"+token;
			 headers.put("sec-websocket-protocol", authHeader);
			LegalSocketClient  client = new  LegalSocketClient(serverUri, aiContextManager,iatContext,headers);
	    	client.connect();
//	    	iatContext.setLegalSocketClient(client);
	    	AiContextManager.IatContextMap.put(deviceMac, iatContext);
	    	
//	        while (!client.getReadyState().equals(ReadyState.OPEN)) {
//                System.out.println(getCurrentTimeStr() + "\t IAT连接中");
//                Thread.sleep(1000);
//            }
//	        //打开语音文件持续发送语音二进制流
//	        iatSendHandle.sendData(client,iatContext.getFilePath());
	        
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
 	
// 	@Async(value = "customServiceExecutor" )
    public void sendQuestion(LegalSocketClient client,String question) {
        try {
            JSONObject requestJson=new JSONObject();
            JSONObject header=new JSONObject();  // header参数
            header.put("action","chat");
            header.put("biz","");
            JSONObject payload=new JSONObject(); // payload参数
            payload.put("text",question);
            requestJson.put("header",header);
            requestJson.put("payload",payload);
            String body = requestJson.toString();
              System.err.println(body); // 可以打印看每次的传参明细
              client.send(body);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
   
}